package com.example.demo.config.security.login.usernamepassword;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;

/**
 * 支持key-value和json格式的自定义登陆
 * UsernamePasswordAuthenticationFilter只支持key-value格式的登陆方式
 */
@Slf4j
public class JsonLoginFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("JsonFilter-----Authentication method not supported: " + request.getMethod());
        } else {
            //可以再此处添加验证码验证规则，这是第二种验证码方式，之前已经实现了一种（KaptchaAuthenticationProvider）
            //json格式登陆
            String contentType = request.getContentType();
            if (contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
                ServletInputStream inputStream = null;
                try {
                    inputStream = request.getInputStream();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                JSONObject body = JSONUtil.parseObj(IoUtil.read(inputStream, CharsetUtil.UTF_8));

                Object username = body.get("uname_login_2type_filter");
                Object password = body.get("pwd_login_2type_filter");
                username = username != null ? username.toString().trim() : "";
                password = password != null ? password : "";
                UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
                this.setDetails(request, authRequest);
                Authentication authenticate = this.getAuthenticationManager().authenticate(authRequest);
                log.info("登录用户信息：{}",JSONUtil.toJsonStr(authenticate));;
                return authenticate;
            }else{
                //key-value格式登陆，如前端form表单提交，直接使用父类默认的接收方式
                return super.attemptAuthentication(request, response);
            }

        }

    }
}
